博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JS动态引入js,CSS——动态创建script/link/style标签
阅读量:4124 次
发布时间:2019-05-25

本文共 1414 字,大约阅读时间需要 4 分钟。

一.动态创建link方式

我们可以使用link的方式.如下代码所示.

function addCssByLink(url){	var doc=document;	var link=doc.createElement("link");	link.setAttribute("rel", "stylesheet");    link.setAttribute("type", "text/css");    link.setAttribute("href", url);	var heads = doc.getElementsByTagName("head");	if(heads.length)		heads[0].appendChild(link);	else		doc.documentElement.appendChild(link);}

 

二.动态创建style方式

但是,这样的话,需要加载整个css文件,但是那样有可能浪费一个http请求并占用一个服务器请求数,并等待上一段下载时间,所以,Firebug Lite采取的是将css代码写在js中,然后动态创建style标签的方法,正如下面所示

function addCssByStyle(cssString){	var doc=document;	var style=doc.createElement("style");	style.setAttribute("type", "text/css");	if(style.styleSheet){// IE		style.styleSheet.cssText = cssString;	} else {// w3c		var cssText = doc.createTextNode(cssString);		style.appendChild(cssText);	}	var heads = doc.getElementsByTagName("head");	if(heads.length)		heads[0].appendChild(style);	else		doc.documentElement.appendChild(style);}

这样的话,如果是较少的代码,可以比较方便的实现到动态加载css的效果,但是如果为了方便维护和管理,并没有等待时间限制,使用link方式更加合适

三.动态创建script方式

var script=document.createElement("script");script.setAttribute("type", "text/javascript");script.setAttribute("src", "JustWalking.js");var heads = document.getElementsByTagName("head");if(heads.length)	heads[0].appendChild(script);else	document.documentElement.appendChild(script);

但是这种方式在IE内核的浏览器中支持,在google、360极速、firefox下却不行

四.打印引入style方式

 

document.write("
");

五.打印引入js方式

document.write("");

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载地址:http://felpi.baihongyu.com/

你可能感兴趣的文章
记CSDN访问量10万+
查看>>
Linux下Oracle数据库账户被锁:the account is locked问题的解决
查看>>
记CSDN访问20万+
查看>>
Windows 环境下Webstorm 2020.3 版本在右下角找不到Git分支切换部件的一种解决方法
查看>>
Electron-Vue项目中遇到fs.rm is not a function问题的解决过程
查看>>
飞机换乘次数最少问题的两种解决方案
查看>>
有向无回路图的理解
查看>>
设计模式中英文汇总分类
查看>>
WPF实现蜘蛛纸牌游戏
查看>>
单例模式
查看>>
工厂方法模式
查看>>
模板方法模式
查看>>
数据结构之队列、栈
查看>>
数据结构之树
查看>>
数据结构之二叉树
查看>>
二叉树非递归遍历算法思悟
查看>>
红黑树算法思悟
查看>>
从山寨Spring中学习Spring IOC原理-自动装配注解
查看>>
实例区别BeanFactory和FactoryBean
查看>>
Spring后置处理器BeanPostProcessor的应用
查看>>